package com.ruoyi.web.controller.wnjk.app.registration;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.wnjk.service.InventoryService;
import com.ruoyi.system.wnjk.service.RegistrationInventoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
@RequestMapping("/app/registration/inventory")
public class RegistrationInventoryController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(RegistrationInventoryController.class);

    @Autowired
    private RegistrationInventoryService inventoryService;

    @GetMapping("/remaining")
    public AjaxResult getRemainingStock(
            @RequestParam("registrationId") String registrationId,
            @RequestParam("date") String date) {
        LocalDate localDate;
        try {
            localDate = LocalDate.parse(date);
        } catch (Exception e) {
            return error("日期格式错误，请使用 yyyy-MM-dd");
        }

        LocalDate tomorrow = LocalDate.now().plusDays(1);
        if (!localDate.equals(tomorrow)) {
            return error("只能查询次日的余量");
        }

        try {
            Long available = inventoryService.getAvailableStock(registrationId, localDate);
            return success(available);
        } catch (IllegalArgumentException e) {
            log.warn("无效的挂号ID查询尝试: doctorId={}, date={}", registrationId, date);
            return error(e.getMessage());
        }
    }
}